package com.chaosj.memory.handlers;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chaosj.memory.dto.BlogDto;
import com.chaosj.memory.dto.WxGzhDto;
import com.chaosj.webmagic.IScrapeHandler;
import com.chaosj.webmagic.scrape.BlogSiteHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.Optional;
import java.util.ServiceLoader;

/**
 * @className: ScapeSiteHandler
 * @description:
 * @author: caoyangjie
 * @date: 2022/1/4
 **/
@Slf4j
public class ScrapeSiteHandler extends AbstractToolHandler<BlogDto>{
    BlogSiteHandler handler;
    @Override
    public String name() {
        return "pack";
    }

    @Override
    public void handler(BlogDto req, StringBuffer outBuffer) {
        req.getScrapes().stream().forEach(url->{
            if( handler == null ){
                ServiceLoader.load(IScrapeHandler.class).forEach(handler->{
                    if( handler instanceof BlogSiteHandler ){
                        this.handler = (BlogSiteHandler) handler;
                    }
                });
            }
            Optional.ofNullable(handler).orElse(new BlogSiteHandler()).setParams(JSONObject.parseObject(JSON.toJSONString(req))).scrape(url);
        });
    }

    @Override
    public BlogDto cmd2Dto(String[] args) {
        return new BlogDto(args);
    }
}
